package com.gylang.print.html;

import cn.hutool.core.collection.CollUtil;
import com.gylang.print.html.emums.HtmlTag;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.jsoup.nodes.Element;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.regex.Pattern;

/**
 * @author gylang
 * data 2021/6/16
 */
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public abstract class HTMLRender {

	public static final Pattern DATA_PLACEHOLDER = Pattern.compile("\\{([\\w.]+)}");


	protected Map<String, Object> data;

	protected List<Predicate<Element>> check;


	/**
	 * 渲染的标签类型
	 */
	public abstract String type();

	/**
	 * 渲染
	 *
	 * @param element 当前标签
	 */
	public abstract Element render(Element element, Map<String, Object> data);

	/**
	 * 添加条件判断
	 *
	 * @param elementPredicate 条件
	 */
	public void addCondition(Predicate<Element> elementPredicate) {

		if (null == check) {
			check = new ArrayList<>();
		}
		check.add(elementPredicate);
	}

	public static boolean hasCollection(Element html) {

		for (HtmlTag htmlTag : HtmlTag.COLLECTION_TAG) {
			if (CollUtil.isNotEmpty(html.children().select(htmlTag.getLabel()))) {
				return true;
			}
		}
		return false;
	}
}
